/*
 * Copyright (c) 2007 Team and Concepts Limited.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Team and Concepts Limited nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY TEAM AND CONCEPTS LIMITED ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL TEAM AND CONCEPTS LIMITED BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.editgrid.api.client;

import org.apache.commons.httpclient.*;
import java.util.*;
import java.text.*;
import org.w3c.dom.*;
import java.io.*;

public class AtomEntry {
	private URI editUri;
	private String resourceType;
	private String resourcePath;
	protected HashMap<String, String> editGridElements = new HashMap<String, String>();
	private boolean isCreate = true;
	
	public HashMap<String, String> getEditGridElements() {
		return this.editGridElements;
	}
	
	public String getResourceType() {
		return this.resourceType;
	}
	
	public String getResourcePath() {
		return this.resourcePath;
	}
	
	public URI getEditUri() {
		return this.editUri;
	}
	
	public boolean getIsCreate() {
		return this.isCreate;
	}
	
	protected static AtomEntry loadXml(Element element) throws URIException {
		AtomEntry entry = new AtomEntry();
		entry.loadXml(new ArrayList<String>(), element);
		return entry;
	}
	
	protected void loadXml(List<String> elementStack, Element element) throws URIException {
		this.isCreate = false;
		
		NodeList nodeList = element.getChildNodes();
		boolean hasInnerElement = false;
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node n = nodeList.item(i);
			if (n.getNodeType() == Node.ELEMENT_NODE) {
				hasInnerElement = true;
				Element e = (Element) n;
				if (e.getNamespaceURI().equals(EditGridService.properties.getProperty("EditGridNS"))) {
					elementStack.add(e.getLocalName());
					this.loadXml(elementStack, e);
				} else if (AtomUtil.isAtomElement(e, "id")) {
					String text = e.getTextContent();
					int pos = text.indexOf(':');
					this.resourceType = text.substring(0, pos);
					this.resourcePath = text.substring(pos+1);
				} else if (AtomUtil.isAtomElement(e, "link") &&
						e.getAttribute("rel").equals("edit")) {
					this.editUri = new URI(e.getAttribute("href"), true);
				}
			}
		}
		
		if (!hasInnerElement) {
			StringBuilder sb = new StringBuilder();
			for (Iterator<String> i = elementStack.iterator(); i.hasNext();) {
				String name = i.next();
				sb.append(name);
				sb.append('.');
			}
			if (sb.length() > 0) sb.deleteCharAt(sb.length()-1);
			this.editGridElements.put(sb.toString(), element.getTextContent());
		}
		if (elementStack.size() > 0) {
			elementStack.remove(elementStack.size() - 1);
		}
	}
	
	public String toAtomAsString() throws IOException {
		Writer writer = new StringWriter();
		XmlWriter w = new XmlWriter(writer);
		w.writeStartElement("entry");
		w.writeAttributeString("xmlns", EditGridService.properties.getProperty("AtomNS"));
		w.writeAttributeString("xmlns", "eg", EditGridService.properties.getProperty("EditGridNS"));
		for (Iterator<Map.Entry<String, String>> i = this.editGridElements.entrySet().iterator(); i.hasNext();) {
			Map.Entry<String, String> entry = i.next();
			w.writeStartElement("eg", entry.getKey());
			w.writeString(entry.getValue());
			w.writeEndElement();
		}
		w.writeEndElement();
		w.close();
		return writer.toString();
	}
	
	public String toRequestPath() {
		return this.resourceType + "/" + this.resourcePath;
	}
	
	public void setValue(String key, String value) {
		this.editGridElements.put(key, value);
	}
	
	public String getValue(String key) {
		return this.editGridElements.get(key);
	}
	
	public int getIntValue(String key) {
		return Integer.parseInt(this.getValue(key));
	}
	
	public long getLongValue(String key) {
		return Long.parseLong(this.getValue(key));
	}
	
	public Date getDatetimeValue(String key) throws ParseException {
		DateFormat df = new SimpleDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'");
		return df.parse(this.getValue(key));
	}
	
	public boolean getBooleanValue(String key) {
		return AtomUtil.AsBoolValue(this.getValue(key));
	}
	
	public String toString() {
		return this.resourceType + "/" + this.resourcePath;
	}
}
